package com.yuxuan.action;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@ServerEndpoint(value = "/web/log")
public class WebLogWebsocket {

    private Process process = null;
    private InputStream inputStream = null;

    private BufferedReader reader;

    private static ExecutorService executors = Executors.newFixedThreadPool(8);

    @OnOpen
    public void onOpen(Session session) {
        try {
            String serverid = session.getQueryString();
            if(serverid.length() != 13){
                return ;
            }
            String dir = serverid.split("=")[1];
            process = Runtime.getRuntime().exec("tail -f /usr/local/server/"+dir+"/lsxapp.log");
            inputStream = process.getInputStream();
            this.reader = new BufferedReader(new InputStreamReader(inputStream));
            executors.execute(new Runnable() {
                @Override
                public void run() {
                    String line = "";
                    try {
                        while ((line = reader.readLine()) != null) {
                            // 将实时日志通过WebSocket发送给客户端，给每一行添加一个HTML换行
                            session.getBasicRemote().sendText(line + "<br>");
                        }
                    } catch (IOException e) {
                        try {
                            session.close();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (process != null) {
            process.destroy();
        }
    }


    @OnError
    public void onError(Throwable thr) {
        thr.printStackTrace();
    }


}
